<template>
    <div class="search">
        <Row>
            <Col>
                <Card>
                    <Row @keydown.enter.native="handleSearch">
                        <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
                            <Form-item label="行政区域" prop="withDepartment">
                                <treeselect v-model="searchForm.withDepartment" :multiple="false" :options="options" style="width: 200px" placeholder="请输入行政区"/>
                                <!--<Input type="text" v-model="searchForm.withDepartment" placeholder="请输入行政区域" clearable style="width: 200px"/>-->
                            </Form-item>
                            <Form-item label="河流名称" prop="riverName">
                                <Input type="text" v-model="searchForm.riverName" placeholder="请输入河流名称" clearable style="width: 200px"/>
                            </Form-item>
                            <Form-item label="巡河人员" prop="userName">
                                <Input type="text" v-model="searchForm.userName" placeholder="请输入巡河人员姓名" clearable style="width: 200px"/>
                            </Form-item>
                            <Form-item style="margin-left:-35px;" class="br">
                                <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                <Button @click="handleReset">重置</Button>
                            </Form-item>
                        </Form>
                    </Row>
                    <Row class="operation">
                        <Button @click="add" type="primary" icon="md-add">添加</Button>
                        <Button @click="delAll" icon="md-trash">批量删除</Button>
                        <Button @click="getDataList" icon="md-refresh">刷新</Button>
                    </Row>
                    <Row>
                        <Alert show-icon>
                            已选择 <span class="select-count">{{selectCount}}</span> 项
                            <a class="select-clear" @click="clearSelectAll">清空</a>
                        </Alert>
                    </Row>
                    <Row>
                        <Table :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom" @on-sort-change="changeSort" @on-selection-change="changeSelect"></Table>
                    </Row>
                    <Row type="flex" justify="end" class="page">
                        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
                    </Row>
                </Card>
            </Col>
        </Row>
        <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="500">
            <Form ref="form" :model="form" :label-width="100" :rules="formValidate" >
                <FormItem label="行政区域" >
                  <department-tree-choose  @on-change="handleSelectDepTree" :multiple="false" ref="depTree"></department-tree-choose>
                </FormItem>
                <FormItem label="河流名称" prop="riverName" >
                <Input v-model="form.riverName" style="width:100%"/>
            </FormItem>
                <FormItem label="巡河人员" prop="users" >
                    <Select v-model="form.users" multiple :max-tag-count="4" :max-tag-placeholder="maxTagPlaceholder">
                        <Option v-for="item in userList" :value="item.id" :key="item.id" :label="item.username">
                            <span style="margin-right:10px;">{{ item.username }}</span>
                            <span style="color:#ccc;">{{ item.departmentTitle }}</span>
                        </Option>
                    </Select>
                </FormItem>
            <FormItem label="河流级别" prop="rank" >
                <Input v-model="form.rank" style="width:100%"/>
            </FormItem>
            <FormItem label="河流类型" prop="type" >
                <Select v-model="form.type" placeholder="请选择" clearable style="width: 100%">
                    <Option value="0">河流</Option>
                    <Option value="1">沟渠</Option>
                    <Option value="2">水库</Option>
                </Select>
            </FormItem>
                <div
                        v-for="(item, index) in form.riverDetail"
                        v-if="item.status"
                        :key="index"
                        :id="index"
                        >
                <br/>
                    <p>河流详细:</p>
                        <FormItem label="河道所在镇 (街道)" label-width="130" label-position ="left" >
                            <Select v-model="item.riverLocation" @on-change="depsSelectChange($event,index)" >
                                <Option v-for="item in depsList" :value="item.id" :key="item.id" :label="item.title">
                                    <span style="margin-right:10px;">{{ item.title }}</span>
                                </Option>
                            </Select>
                        </FormItem>
                    <!--villageList-->
                        <FormItem label="河道流经村名称 " label-width="130" label-position="left">
                            <Select v-model="item.approachVillage" >
                                <Option v-for="items in item.villageList" :value="items.id" :key="items.id" :label="items.title">
                                    <span style="margin-right:10px;">{{ items.title }}</span>
                                </Option>
                            </Select>
                                <!--<Input type="text" v-model="item.approachVillage" placeholder="河道流经村名称"></Input>-->
                        </FormItem>
                        <FormItem label="镇域河道起止位置" label-width="130" label-position ="left" :prop="'riverDetail.' + index + '.startStopPosition'"
                                  :rules="{required: true, message: '请输入镇域河道起止位置', trigger: 'blur'}" >
                                <Input type="text" v-model="item.startStopPosition" placeholder="镇域河道起止位置"></Input>
                        </FormItem>
                        <!--<FormItem label="巡河人员" label-width="130" label-position ="left" :prop="'riverDetail.' + index + '.userId'"
                                  :rules="{required: true, message: '请输入用户', trigger: 'blur'}" >
                                <Select v-model="item.userId" >
                                    <Option v-for="item in userList" :value="item.id" :key="item.id" :label="item.username">
                                        <span style="margin-right:10px;">{{ item.username }}</span>
                                        <span style="color:#ccc;">{{ item.departmentTitle }}</span>
                                    </Option>
                                </Select>
                        </FormItem>-->
                            <Button @click="handleRemove(index)">删除</Button>
                    <br/>
                </div>
                <FormItem>
                    <Row>
                        <Col span="12">
                            <Button type="dashed" long @click="handleAdd" icon="md-add">添加河流详细</Button>
                        </Col>
                    </Row>
                </FormItem>
                <!--<FormItem label="巡河人员" prop="userIds" >-->
                    <!--<Select v-model="form.userIds" multiple>-->
                        <!--<Option v-for="item in userList" :value="item.id" :key="item.id" :label="item.username">-->
                            <!--<span style="margin-right:10px;">{{ item.username }}</span>-->
                            <!--<span style="color:#ccc;">{{ item.departmentTitle }}</span>-->
                        <!--</Option>-->
                    <!--</Select>-->
                <!--</FormItem>-->
            </Form>
            <div slot="footer">
                <Button type="text" @click="modalVisible=false">取消</Button>
                <Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {
        getAllUserData,
        loadDepartment,
        allDepartmentVillage,
        getDeptTrees
    } from "@/api/index";
    import Treeselect from '@riophae/vue-treeselect';
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    import {
        getdeps
    } from "@/api/activiti";
    import departmentTreeChoose from "@/views/my-components/xboot/department-tree-choose";
    export default {
        name: "river",
        components: {
            Treeselect,
            departmentTreeChoose
        },
        data() {
            return {
                loading: true, // 表单加载状态
                modalType: 0, // 添加或编辑标识
                modalVisible: false, // 添加或编辑显示
                modalTitle: "", // 添加或编辑标题
                options: [],
                userList:[],
                depsList:[],//所有镇
                villageList:[], //镇下面所有村/全部
                searchForm: { // 搜索框初始化对象
                    pageNumber: 1, // 当前页数
                    pageSize: 10, // 页面大小
                    sort: "create_time", // 默认排序字段
                    order: "desc", // 默认排序方式
                },
                index: 1,
                form: { // 添加或编辑表单对象初始化数据
                    withDepartment: "",
                    riverName: "",
                    departmentId:"",
                    users:[],
                    // userIds:[],
                    riverDetail:[
                        {
                            riverLocation: '',
                            index: 1,
                            status: 1,
                            startStopPosition:'',
                            approachVillage:'',
                            userId:'',
                            villageList:[]
                        }
                    ]
                },
                // 表单验证规则
                formValidate: {
                    riverName: [{ required: true, message: "河流名称不能为空", trigger: "blur" }],
                    withDepartment: [{ required: true, message: "行政区域不能为空", trigger: "change" }],
                    type: [{ startStopPosition: true, message: "请输入河流类型", trigger: "change" }],
                },
                submitLoading: false, // 添加或编辑提交状态
                selectList: [], // 多选数据
                selectCount: 0, // 多选计数
                columns: [
                    // 表头
                    {
                        type: "selection",
                        width: 60,
                        align: "center"
                    },
                    {
                        type: "index",
                        width: 60,
                        align: "center"
                    },
                    {
                        title: "河流编码",
                        key: "id",
                        minWidth: 120,
                        sortable: false,
                    },
                    {
                        title: "行政区域",
                        key: "withDepartmentName",
                        minWidth: 120,
                        sortable: false,
                    },
                    {
                        title: "河流名称",
                        key: "riverName",
                        minWidth: 120,
                        sortable: false,
                    },
                    {
                        title: "操作",
                        key: "action",
                        align: "center",
                        width: 200,
                        render: (h, params) => {
                            return h("div", [
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small",
                                            icon: "ios-create-outline"
                                        },
                                        style: {
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.edit(params.row);
                                            }
                                        }
                                    },
                                    "编辑"
                                ),
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "error",
                                            size: "small",
                                            icon: "md-trash"
                                        },
                                        on: {
                                            click: () => {
                                                this.remove(params.row);
                                            }
                                        }
                                    },
                                    "删除"
                                )
                            ]);
                        }
                    }
                ],
                data: [], // 表单数据
                total: 0 // 表单数据总数
            };
        },
        methods: {
            init() {
                this.getDataList();
            },
            maxTagPlaceholder (num) {
                return '等'+ num +'人';
            },
            depsSelectChange(e,index){
                if(e!=undefined){
                    if(index == 0){
                        this.form.riverDetail[0].villageList = [];
                    }
                    loadDepartment(e).then(res => {
                        if (res.success) {
                                this.form.riverDetail[index].villageList = res.result;
                        }
                    });
                }

            },
            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getDataList();
                this.clearSelectAll();
            },
            handleRemove (index) {
                this.form.riverDetail[index].status = 0;
            },
            handleAdd () {
                this.index++;
                this.form.riverDetail.push(
                        {
                            riverLocation: '',
                            index: this.index,
                            status: 1,
                            startStopPosition:'',
                            approachVillage:'',
                            villageList:[]
                        });
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getDataList();
            },
            handleSearch() {
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getDataList();
            },
            handleReset() {
                this.$refs.searchForm.resetFields();
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                // 重新加载数据
                this.getDataList();
            },
            changeSort(e) {
                this.searchForm.sort = e.key;
                this.searchForm.order = e.order;
                if (e.order === "normal") {
                    this.searchForm.order = "";
                }
                this.getDataList();
            },
            clearSelectAll() {
                this.$refs.table.selectAll(false);
            },
            changeSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            getDataList() {
                this.loading = true;
                // 带多条件搜索参数获取表单数据 请自行修改接口
                this.getRequest("/river/getByPage", this.searchForm).then(res => {
                    this.loading = false;
                    if (res.success) {
                        this.data = res.result.records;
                        this.total = res.result.total;
                    }
                });
                // 以下为模拟数据
                //this.data = [
                //];
                this.total = this.data.length;
                this.loading = false;
            },

            handleSubmit() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        let remeRover=[];
                        this.form.riverDetail.forEach(e => {
                            if (e.status != 0) {
                                remeRover.push(e);
                            }
                        });
                        this.form.riverDetail =JSON.stringify(remeRover);
                        this.submitLoading = true;
                        if (this.modalType === 0) {
                            // 添加 避免编辑后传入id等数据 记得删除
                            delete this.form.id;
                            delete this.form.riverUser;
                            delete this.form.equipments;
                            this.postRequest("/river/insertOrUpdate", this.form).then(res => {
                                this.submitLoading = false;
                                if (res.success) {
                                    this.$Message.success("操作成功");
                                    this.getDataList();
                                    this.modalVisible = false;
                                    this.index=1
                                    this.form.riverDetail=[
                                            {
                                                riverLocation: '',
                                                index: 1,
                                                status: 1,
                                                startStopPosition:'',
                                                approachVillage:'',
                                                userId:''
                                            }
                                        ]
                                }
                            });
                            // 模拟请求成功
                            this.submitLoading = false;
                            this.getDataList();
                            this.searchVillage();//获取所有村
                            this.modalVisible = false;
                        } else {
                            // 编辑
                            delete this.form.riverUser;
                            delete this.form.equipments;
                            this.postRequest("/river/insertOrUpdate", this.form).then(res => {
                                this.submitLoading = false;
                                if (res.success) {
                                    this.$Message.success("操作成功");
                                    this.getDataList();
                                    this.modalVisible = false;
                                    this.index=1
                                    this.form.riverDetail=[
                                        {
                                            riverLocation: '',
                                            index: 1,
                                            status: 1,
                                            startStopPosition:'',
                                            approachVillage:'',
                                            userId:''
                                        }
                                    ]
                                }
                            });
                            // 模拟请求成功
                            this.submitLoading = false;
                            this.getDataList();
                            this.searchVillage();//获取所有村
                            this.modalVisible = false;
                        }
                    }

                });
            },

            add() {
                this.$refs.depTree.setData([], "");
                this.modalType = 0;
                this.modalTitle = "添加";
                this.$refs.form.resetFields();
                delete this.form.id;
                this.form.riverDetail=[
                    {
                        riverLocation: '',
                        index: 1,
                        status: 1,
                        startStopPosition:'',
                        approachVillage:'',
                        userId:'',
                        villageList:[]
                    }
                ];
                this.modalVisible = true;
            },
            edit(v) {
                this.modalType = 1;
                this.modalTitle = "编辑";
                this.$refs.form.resetFields();
                let userids =[]
                // 转换null为""
                for (let attr in v) {
                    if (v[attr] === null) {
                        v[attr] = "";
                    }
                }
                if(v.riverUser !== null && v.riverUser.length>0 ) {
                    for (let attr=0;attr<v.riverUser.length;attr++) {
                       let vills = this.villageList.filter(value => {return value.parentId==v.riverUser[attr].riverLocation});
                        userids.push({
                            riverLocation: v.riverUser[attr].riverLocation,
                            index: attr+1,
                            status: 1,
                            startStopPosition:v.riverUser[attr].startStopPosition,
                            approachVillage:v.riverUser[attr].approachVillage,
                            userId:v.riverUser[attr].userId,
                            villageList:vills
                        })
                        // userids.push(v.userIds[attr].id);啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
                    }
                }
                let str = JSON.stringify(v);
                let data = JSON.parse(str);
                this.form = data;
                this.form.users = data.users.split(",");
                this.$refs.depTree.setData([data.withDepartment], data.withDepartmentName);
                this.form.riverDetail = userids;
                this.modalVisible = true;
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    // 记得确认修改此处
                    content: "您确认要删除 " + v.name + " ?",
                    loading: true,
                    onOk: () => {
                        // 删除
                        this.deleteRequest("/river/delByIds/" + v.id).then(res => {
                          this.$Modal.remove();
                          if (res.success) {
                            this.$Message.success("操作成功");
                            this.getDataList();
                            this.searchVillage();//获取所有村
                          }
                        });
                        // 模拟请求成功
                        this.$Modal.remove();
                    }
                });
            },
            handleSelectDepTree(v) {
                this.form.withDepartment = v[0];
            },
            getUserAll() {
                getAllUserData().then(res => {
                    if (res.success) {
                        this.userList = res.result;
                    }
                });
            },
            getDepsList(){
                getdeps().then(res => {
                    if (res.success) {
                        this.depsList = res.result.departments;
                    }
                });

            },
            searchVillage(){
                    allDepartmentVillage().then(res => {
                    if (res.success) {
                        this.villageList = res.result;
                    }
                });

            },
            delAll() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要删除的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
                    loading: true,
                    onOk: () => {
                        let ids = "";
                        this.selectList.forEach(function(e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        // 批量删除
                        this.deleteRequest("/river/delByIds/" + ids).then(res => {
                          this.$Modal.remove();
                          if (res.success) {
                            this.$Message.success("操作成功");
                            this.clearSelectAll();
                            this.getDataList();
                            this.searchVillage();//获取所有村
                          }
                        });
                        // 模拟请求成功
                        // this.$Message.success("操作成功");
                        this.$Modal.remove();
                    }
                });
            },
            deptsTree(){
                getDeptTrees().then(res => {
                    if (res.success) {
                        this.options = res.result;
                    }
                });
            },
        },
        mounted() {
            // 计算高度
            this.height = Number(document.documentElement.clientHeight - 230);
            this.init();
            this.getUserAll();
            this.getDepsList();//获取所有镇
            this.searchVillage();//获取所有村
            this.deptsTree();
        }
    };
</script>
<style lang="less">
    .search {
        .operation {
            margin-bottom: 2vh;
        }
        .select-count {
            font-size: 13px;
            font-weight: 600;
            color: #40a9ff;
        }
        .select-clear {
            margin-left: 10px;
        }
        .page {
            margin-top: 2vh;
        }
        .drop-down {
            font-size: 13px;
            margin-left: 5px;
        }
    }
</style>